<template>
  <div class="order-check-form">
    <div class="status">
      <a-tag color="orange" v-if="deliveryId">
        送货单ID：{{deliveryId}}
      </a-tag>
      <a-tag color="green" v-else>
        未送货
      </a-tag>
    </div>
    <a-form :form="form" layout="horizontal" autoComplete="off">
      <a-form-item label="客户ID">
        <a-input
          v-decorator="['clientId',
            { rules: [{ required: true, message: '请勿删除或修改客户ID' }]}]"
          disabled
        />
      </a-form-item>
      <a-form-item label="订单ID">
        <a-input
          v-decorator="['id',
           { rules: [{ required: true, message: '请勿删除或修改订单ID' }]}]"
          disabled
        />
      </a-form-item>
      <a-form-item label="客户PO">
        <a-input
          v-decorator="['po']"
          placeholder="客户PO"
        />
      </a-form-item>
      <a-form-item label="客方货号">
        <a-input
          v-decorator="['goodsNumber']"
          placeholder="客方货号"
        />
      </a-form-item>
      <a-form-item label="盒式">
        <a-input
          v-decorator="['goodsType']"
          placeholder="盒式"
        />
      </a-form-item>
      <a-form-item label="纸质">
        <a-input
          v-decorator="['quality']"
          placeholder="纸质"
        />
      </a-form-item>
      <a-form-item label="规格">
        <a-input
          v-decorator="['size',
            { rules: [
              { validator: sizeValidator }
            ]},
           ]"
          placeholder="规格"
        />
      </a-form-item>
      <a-form-item label="数量">
        <a-input
          v-decorator="['quantity',
            { rules: [
              {type: 'integer', message: '数量必须是正整数'}
            ]},
          ]"
          placeholder="数量"
          @blur="e => handleChange(e.target.value, 'quantity')"
        />
      </a-form-item>
      <a-form-item label="单价">
        <a-input
          v-decorator="['price',
            { rules: [
              {pattern: Decimal3Places, message: '单价必须是3位小数，输入其它数字会转化成3位小数'}
            ]},
          ]"
          placeholder="单价"
          @blur="e => handleChange(e.target.value, 'price')"
        />
      </a-form-item>
      <a-form-item label="金额">
        <a-input
          v-decorator="['amount']"
          placeholder="金额"
          disabled
        />
      </a-form-item>
      <a-form-item label="备注">
        <a-input
          v-decorator="['remark']"
          placeholder="备注"
        />
      </a-form-item>
      <a-form-item>
        <div class="operations">
          <a-popconfirm
            title="确认修改该订单信息？"
            ok-text="确认修改"
            cancel-text="取消"
            @confirm="handleSubmit"
          >
            <a-button type="primary">
              提交
            </a-button>
          </a-popconfirm>
          <a-button @click="handleCancel">
            取消
          </a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import {
  fixed3Float,
  fixedInt,
  times3IntFixed,
  divide3Float3Fixed,
  times3FixedFloatInt,
  positiveInteger
} from '@/utils/NumberChange.js';

import {
  Decimal3Places,
  sizePattern
} from '@/utils/pattern.js';

import {
  orderCheckReq,
  orderUpdateReq,
  orderUpdateDeliveredReq
} from '@/requests/orderRequests';

import {
  isNull
} from '@/utils/commonFunc.js';

export default {
  name: "OrderCheckForm",
  props: {

  },
  data() {
    return {
      Decimal3Places,
      form: this.$form.createForm(this, { name: 'orderCheckForm' }),
      deliveryId: null,
    };
  },
  computed: {
    id() {
      return this.$route.params.id;  
    },
  },
  mounted() {
    // 设置 form 的初始值
    if (this.id !== undefined && this.$route.name == "OrderCheck") {
      const loaded = this.$message.loading('正在加载订单数据', 0);
      this.checkOrder().then((res) => {
        loaded();
        const order = res.data;
        if (!isNull(order.deliveryId)) {
          this.deliveryId = order.deliveryId;
        }
        this.form.setFieldsValue({
          ['clientId']: order.clientId,
          ['id']: order.id,
          ['po']: order.po,
          ['goodsNumber']: order.goodsNumber,
          ['goodsType']: order.goodsType,
          ['quality']: order.quality,
          ['size']: order.size,
          ['quantity']: order.quantity,
          ['price']: divide3Float3Fixed(order.price),
          ['amount']: divide3Float3Fixed(order.amount),
          ['remark']: order.remark
        })
      }).catch((err) => {
        loaded();
        this.$notification['error']({
          message: '修改订单',
          description:
            `获取订单失败，错误提示 ${err.response.data.message}`,
        });
      });
    }
    
  },
  watch: {

  },
  methods: {
    /**
     * 查询用户信息
     */
    checkOrder() {
      const id = this.id;
      return orderCheckReq(id);
    },
    /**
     * 提交OrderCheck表单
     */
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          // 向后端发起修改订单请求
          const orderId = this.id;
          const order = Object.assign({}, values);
          delete order.clientId;
          delete order.id;
          order.price = times3IntFixed(order.price);
          order.amount = times3IntFixed(order.amount);

          const loaded = this.$message.loading('正在修改订单数据，请勿重复提交', 0);
          const deliveryed = !isNull(this.deliveryId);
          // 如果是未送货订单
          if (!deliveryed) {
            orderUpdateReq(orderId, order).then((res) => {
              loaded();
              // 如果成功，应当得到一个orderId，应当是这个订单的id
              const order = res.data;
              const orderId = order.id;

              // 由于无法直接刷新页面，所以需要首先回退到订单主页
              this.$router.push({
                name: 'OrderIndex'
              });

              // 弹出修改客户信息成功的提示框
              this.$notification['success']({
                message: '修改订单信息',
                description:
                  `修改订单信息成功，订单ID ${orderId}`,
              });

              this.$store.commit('updateOrdersCache');
            }).catch((err) => {
              loaded();
              this.$notification['error']({
                message: '修改订单',
                description:
                  `修改订单失败，错误提示 ${err.response.data.message}`,
              });
            });
          }
          // 如果是已送货订单
          else {
            orderUpdateDeliveredReq(orderId, order).then((res) => {
              loaded();
              // 如果成功，应当得到一个orderId，应当是这个订单的id
              const order = res.data;
              const orderId = order.id;

              // 由于无法直接刷新页面，所以需要首先回退到订单主页
              this.$router.go(-1);

              // 弹出修改客户信息成功的提示框
              this.$notification['success']({
                message: '修改订单信息',
                description:
                  `修改已送货订单信息成功，订单ID ${orderId}`,
              });

              this.$store.commit('updateOrdersCache');
              this.$store.commit('updateDeliveriesCache');
            }).catch((err) => {
              loaded();
              this.$notification['error']({
                message: '修改订单',
                description:
                  `修改订单失败，错误提示 ${err.response.data.message}`,
              });
            });
          }
        }
      });
    },
    /**
     * 放弃表单修改，回到上一页，并通知上层重置表单的key
     */
    handleCancel() {
      this.$emit('handleCancel');
    },
    sizeValidator(rule, value, callback) {
      const pattern = sizePattern;
      if (!pattern.test(value)) {
        return callback(new Error(`只能输入 '正整数x正整数x正整数' 或 '正整数x正整数' 或 '正整数' 格式的字符串，或者将正整数改成一位小数`))
      }
      else {
        return callback()
      }
      callback()
    },
    /**
     * handleChange 只用来处理 price 和 quantity
     * @param value 输入框里的值
     * @param fieldName 输入框所属的表单项
     * 
    */ 
    handleChange(value, fieldName) {
      const TwoFloatArray = ['price'];
      const IntArray = ['quantity'];

      // 将 price 转化为 2位小数
      if (TwoFloatArray.includes(fieldName)) {
        value = fixed3Float(value);
        this.form.setFieldsValue({
          [fieldName]: value
        })
      }

      // 将 quantity 转化为 正整数
      if (IntArray.includes(fieldName)) {
        value = fixedInt(value);
        this.form.setFieldsValue({
          [fieldName]: value
        })
      }

      // 计算 amount
      const price = fixed3Float(this.form.getFieldValue('price'));
      const quantity = fixedInt(this.form.getFieldValue('quantity'));
      const amount = times3FixedFloatInt(price, quantity)
      this.form.setFieldsValue({
        ['amount']: amount
      })
    },
    isNull
    
  },
  components: {

  },
};
</script>

<style scoped lang="scss">
.order-check-form {
  .status {
    display: flex;
    justify-content: flex-end;
    margin: 0 30px 10px 0;
  }

  .ant-form-item:not(:last-child) {
    display: grid;
    grid-template-columns: 0 100px 500px 0;
  }

  .ant-form-item:last-child {
    display: grid;
    grid-template-columns: 450px 150px 0;
    align-items: center;

    .operations {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
<style lang="scss">
.order-check-form {
  form {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

</style>
